<template>
  <div class="pet-list-container">
    <div class="page-header">
      <h1>🐕 宠物浏览</h1>
      <p>选择您心仪的宠物</p>
    </div>

    <!-- 筛选栏 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="宠物类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="狗" value="dog"></el-option>
            <el-option label="猫" value="cat"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品种">
          <el-input v-model="searchForm.breed" placeholder="请输入品种" clearable></el-input>
        </el-form-item>
        <el-form-item label="价格范围">
          <el-select v-model="searchForm.priceRange" placeholder="请选择" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="1000以下" value="0-1000"></el-option>
            <el-option label="1000-3000" value="1000-3000"></el-option>
            <el-option label="3000-5000" value="3000-5000"></el-option>
            <el-option label="5000以上" value="5000-"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 宠物列表 -->
    <div class="pet-list">
      <el-row :gutter="20">
        <el-col :span="6" v-for="pet in petList" :key="pet.id">
          <el-card :body-style="{ padding: '0px' }" shadow="hover" class="pet-card" @click.native="handleViewDetail(pet)">
            <div class="pet-image-wrapper">
              <img :src="pet.image" class="pet-image">
              <el-tag :type="getStatusType(pet.status)" class="status-tag">
                {{ pet.status }}
              </el-tag>
            </div>
            <div class="pet-content">
              <h3>{{ pet.name }}</h3>
              <div class="pet-detail">
                <el-descriptions :column="1" size="small">
                  <el-descriptions-item label="品种">{{ pet.breed }}</el-descriptions-item>
                  <el-descriptions-item label="年龄">{{ pet.age }}个月</el-descriptions-item>
                  <el-descriptions-item label="性别">{{ pet.gender }}</el-descriptions-item>
                </el-descriptions>
              </div>
              <div class="pet-footer">
                <span class="price">¥{{ pet.price }}</span>
                <el-button type="primary" size="small" @click.stop="handleBuy(pet)">
                  立即购买
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[8, 16, 24, 32]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getPetList } from '@/api/pet'

export default {
  name: 'PetList',
  data () {
    return {
      loading: false,
      searchForm: {
        type: '',
        breed: '',
        priceRange: ''
      },
      petList: [],
      pagination: {
        currentPage: 1,
        pageSize: 8,
        total: 0
      }
    }
  },
  created () {
    this.loadPetList()
  },
  methods: {
    loadPetList () {
      this.loading = true
      const params = {
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      // 添加筛选条件
      if (this.searchForm.type) {
        params.category = this.searchForm.type
      }
      if (this.searchForm.breed) {
        params.keyword = this.searchForm.breed
      }
      // 处理价格范围
      if (this.searchForm.priceRange) {
        const priceRange = this.searchForm.priceRange
        if (priceRange === '0-1000') {
          params.minPrice = 0
          params.maxPrice = 1000
        } else if (priceRange === '1000-3000') {
          params.minPrice = 1000
          params.maxPrice = 3000
        } else if (priceRange === '3000-5000') {
          params.minPrice = 3000
          params.maxPrice = 5000
        } else if (priceRange === '5000-') {
          params.minPrice = 5000
        }
      }
      getPetList(params).then(res => {
        this.loading = false
        if (res && res.data) {
          const data = res.data.records || res.data.list || res.data || []
          console.log('宠物列表原始数据:', data.length > 0 ? data.slice(0, 2) : '无数据') // 调试日志
          this.petList = data.map(item => ({
            id: item.id,
            // 宠物名称 - 后端返回 petName
            name: item.petName || item.pet_name || item.name || '未命名',
            // 品种
            breed: item.breed || '未知品种',
            // 年龄
            age: item.age || 0,
            // 性别 - 后端返回 genderText（已转换为文字）
            gender: item.genderText || item.gender_text || item.gender || '未知',
            // 价格
            price: item.price || 0,
            // 状态 - 后端返回 petStatusText（已转换为文字）
            status: item.petStatusText || item.pet_status_text || item.statusName || item.status || '可售',
            // 图片 - 后端返回 imageUrl 或 mainImage
            image: item.imageUrl || item.image_url || item.mainImage || item.main_image || item.image || require('@/assets/logo.png')
          }))
          this.pagination.total = res.data.total || data.length
          console.log('处理后的宠物数据:', this.petList.length, '条') // 调试日志
          if (this.petList.length === 0) {
            this.$message.warning({ message: '暂无宠物数据', duration: 800 })
          }
        }
      }).catch(err => {
        this.loading = false
        console.error('加载宠物列表失败：', err)
        this.$message.error({ message: '加载宠物列表失败', duration: 800 })
      })
    },
    handleSearch () {
      console.log('搜索', this.searchForm)
      this.loadPetList()
    },
    handleReset () {
      this.searchForm = {
        type: '',
        breed: '',
        priceRange: ''
      }
      this.loadPetList()
    },
    handleViewDetail (pet) {
      this.$router.push({ path: '/user/pet-detail', query: { id: pet.id } })
    },
    handleBuy (pet) {
      this.$confirm(`确认购买 ${pet.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success({ message: '购买成功！', duration: 800 })
      }).catch(() => {
        this.$message.info({ message: '已取消购买', duration: 800 })
      })
    },
    getStatusType (status) {
      const typeMap = {
        '可售': 'success',
        '已售': 'info',
        '预定': 'warning'
      }
      return typeMap[status] || 'info'
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.loadPetList()
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.loadPetList()
    }
  }
}
</script>

<style scoped>
.pet-list-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 32px;
}

.filter-card {
  margin-bottom: 20px;
}

.pet-list {
  margin-bottom: 20px;
}

.pet-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.pet-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.pet-image-wrapper {
  position: relative;
}

.pet-image {
  width: 100%;
  height: 250px;
  object-fit: cover;
}

.status-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

.pet-content {
  padding: 15px;
}

.pet-content h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #333;
}

.pet-detail {
  margin: 10px 0;
}

.pet-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
}
</style>
